<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\User;
use Illuminate\Support\Facades\Redis;

class CabinetAlarmLog extends Model
{
    protected $table = 'xfy_cabinet_alarm_logs';
    protected $primaryKey = 'id';

    const STATUS_YES = 1;
    const STATUS_NO = 0;
    const STATUS_TEXT = ['0' => '未处理', '1' => '已处理'];

    public static function setAlarm(){
        $alarms = CabinetAlarm::where('active', CabinetAlarm::ACTIVE_YES)->get()->toArray();
        if (empty($alarms)) {
            return;
        }
        foreach ($alarms as $oneAlarm) {
            $pointAlias = CabinetPoint::where('id', $oneAlarm['point_id'])->value('alias');
            $newestCacheKey = Cabinet::CACHE_KEY_.$oneAlarm['cabinet_id'];
            $newestCache = Redis::get($newestCacheKey);
            if (empty($newestCache)) {
                continue;
            }
            $newestData = json_decode($newestCache, true);
            $newestValue = round($newestData[$pointAlias], 3);

            //是否存在未处理的报警信息
            $oneLog = self::where('alarm_id', $oneAlarm['id'])->where('status', self::STATUS_NO)->first();
            if ($oneLog) {
                //若存在，看看数值是否正常
                $abnormal = self::judge($oneAlarm['condition'], $newestValue, $oneAlarm['value']);
                if (!$abnormal) {
                    $oneLog->status = self::STATUS_YES;
                    $oneLog->operator = 0;
                    $oneLog->save();
                }
            } else {
                $abnormal = self::judge($oneAlarm['condition'], $newestValue, $oneAlarm['value']);
                if ($abnormal) {
                    $log = new self();
                    $log->project_id = $oneAlarm['project_id'];
                    $log->cabinet_pid = $oneAlarm['cabinet_pid'];
                    $log->cabinet_id = $oneAlarm['cabinet_id'];
                    $log->point_id = $oneAlarm['point_id'];
                    $log->alarm_id = $oneAlarm['id'];
                    $log->alarm_name = $oneAlarm['name'];
                    $log->alarm_level = $oneAlarm['level'];
                    $log->alarm_value = $oneAlarm['value'];
                    $log->real_value = $newestValue;
                    $log->save();
                    self::pushMessage($oneAlarm);
                }
            }
        }
    }

    protected static function pushMessage($oneAlarm){
        $admins = ProjectUser::where('projectId', $oneAlarm['project_id'])->pluck('user_id')->toArray();
        $unionids = AdminUser::whereIn('id', $admins)->where('unionid', '!=', '0')->pluck('unionid')->toArray();
        $openids = User::whereIn('unionid', $unionids)->pluck('openid')->toArray();
        $app = app('wechat.official_account');
        foreach ($openids as $openid) {
            $data = self::genMessageData($oneAlarm, $openid);
            $mini = \EasyWeChat::miniProgram();
            $mini->subscribe_message->send($data);
            // $app->template_message->send($data);
        }
    }

    protected static function genMessageData($oneAlarm, $openid){
        $box = Cabinet::where('id', $oneAlarm['cabinet_pid'])->value('name');
        $cabinet = Cabinet::where('id', $oneAlarm['cabinet_id'])->value('name');
        $device = $box.'-'.$cabinet;
        $point = CabinetPoint::where('id', $oneAlarm['point_id'])->value('name');
        $data = [
            'template_id' => '890vAF2WMqWtWb6s3lkHXgfkWnHJX499DtAtwpyJrEI', // 所需下发的订阅模板id
            'touser' => $openid,     // 接收者（用户）的 openid
            'page' => 'pages/v2/Log/Log',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                'date1' => [
                    'value' => date('Y-m-d H:i',time()),
                ],
                'thing2' => [
                    'value' => $device,
                ],
                'thing3' => [
                    'value' => $oneAlarm['name'],
                ],
            ],
        ];
        // $data = [
        //     'touser' => $openid,
        //     'template_id' => 'wKqlkfSZPuy3G6iRzVAmlPtTVUvYDuN9WNuTNivMYpY',
        //     'miniprogram' => [
        //             'appid' => 'wx301bce58badb7cc3',
        //             'pagepath' => 'pages/v2/Log/Log',
        //     ],
        //     'data' => [
        //         "first" => [
        //             "value" => '设备出现异常请及时关注',
        //             "color" => "#173177"
        //         ],
        //         "keyword1" => [
        //            "value" => date("Y-m-d H:i:s"),
        //            "color" =>"#173177"
        //         ],
        //         "keyword2" => [
        //            "value" => $device,
        //            "color" => "#173177"
        //         ],
        //         "keyword3" =>  [
        //            "value" => $oneAlarm['name'],
        //            "color" => "#173177"
        //         ],
        //         "remark" => [
        //             "value" => $point,
        //             "color" => "#173177"
        //         ]
        //     ],
        // ];
        return $data;
    }

    protected static function judge($cond, $realVal, $presetVal){
        switch ($cond) {
            case '>':
                if ($realVal > $presetVal) {
                    return true;
                } else {
                    return false;
                }
                break;
            case '<':
                if ($realVal < $presetVal) {
                    return true;
                } else {
                    return false;
                }
                break;
            case '>=':
                if ($realVal >= $presetVal) {
                    return true;
                } else {
                    return false;
                }
                break;
            case '<=':
                if ($realVal <= $presetVal) {
                    return true;
                } else {
                    return false;
                }
                break;
            case '=':
                if ($realVal == $presetVal) {
                    return true;
                } else {
                    return false;
                }
                break;
            default:
                break;
        }
    }
}